package com.desin.modle.datastruct.algo.hashtable18;

public class MyHashTable<K,V> {
    private Entry<K,V>[] table ;
    private int size=0;
    private int use=0;
    private static final int INIT_CAP = 8;
    private static final float LOAD_FACTOR=0.75f;

    public MyHashTable(){
        table = (Entry<K, V>[]) new Entry[INIT_CAP];
    }

    static class Entry<K,V>{
        private K key;
        private V value;
        private Entry<K,V> next;

        public Entry(K key,V value,Entry<K,V> entry){
            this.key=key;
            this.value=value;
            this.next=entry;
        }
    }
    public void resize(){

    }

    public int hash(Object k){
        int h;
        return (k==null)?0:((h=k.hashCode())^(h>>>16))%table.length;
    }

    public void put(K key,V value){
        int index = hash(key);
        if( table[index]==null){
            table[index] = new Entry<>(null,null,null);
        }
        Entry<K,V> temp = table[index];
        if(temp.next==null){
            temp.next=new Entry<>(key,value,null);
            size++;
            use++;
            if(use>=table.length*LOAD_FACTOR){
                resize();
            }
        }else{
            while (temp.next!=null){
                temp = temp.next;
                if(temp.key==key){
                    temp.value=value;
                    return;
                }
            }
            Entry entry=table[index].next;
            table[index].next=new Entry<>(key,value,entry);
            size++;
        }
    }

    public V get(K key){
        int index = hash(key);
        Entry<K, V> entry = table[index];
        if(entry==null||entry.next==null){
            return null;
        }
        while (entry.next!=null){
            entry = entry.next;
            if(entry.key==key){
                return entry.value;
            }
        }
        return null;
    }
}
